package alg

import (
	"bufio"
	"fmt"
	"os"
	"sort"
	"strings"
)

func init() {
	RegisterAlgInfo(
		"group-anagrams",
		AlgInfo{
			name: "字母异位词分组",
			url:  "https://leetcode.cn/problems/group-anagrams",
			alg: func() {
				reader := bufio.NewReader(os.Stdin)

				fmt.Print("请输入字符串数组(用逗号分隔，例如 eat,eta,ate): ")
				input, err := reader.ReadString('\n')
				if err != nil {
					fmt.Println("读取输入时发生错误:", err)
					return
				}
				input = strings.TrimSpace(input)
				if input == "" {
					fmt.Println("输入不能为空")
					return
				}

				strs := strings.Split(input, ",")
				for i, str := range strs {
					strs[i] = strings.TrimSpace(str)
					if strs[i] == "" {
						fmt.Println("输入的字符串不能为空")
						return
					}
				}

				res := groupAnagrams(strs)

				fmt.Println("分组结果: ", res)
			},
		})
}

// 思路：对每个字母进行排序，排序后的字母作为 hash 值，匹配上则是字母异位词

func groupAnagrams(strs []string) [][]string {
	sortedMap := make(map[string][]string)
	result := [][]string{}

	for _, str := range strs {
		s := []byte(str)
		sort.Slice(s, func(i, j int) bool { return s[i] < s[j] })
		sortedStr := string(s)
		sortedMap[sortedStr] = append(sortedMap[sortedStr], str)
	}

	for _, v := range sortedMap {
		result = append(result, v)
	}

	return result
}
